--[[

Copyright (c) 2007, Nash Tsai
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

--]]

-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local string = require("string")
local table = require("table")
--module("nashlib.fsm")
local _G = _G
FSM = {}
--module(...)

-----------------------------------------------------------------------------
-- Module version
-----------------------------------------------------------------------------
_VERSION = "FSM 1.0.1"

-----------------------------------------------------------------------------
-- Base Class --
-----------------------------------------------------------------------------
Base  = {
    _name = nil
    }

function Base:new(o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    return o
end

function Base:getName()
    return self._name
end

-----------------------------------------------------------------------------
-- Event Class --
-----------------------------------------------------------------------------
Event = Base:new()
   
--function Event:id()
--   return md5.sum(self._name)
--end

-----------------------------------------------------------------------------
-- Transition Class --
-----------------------------------------------------------------------------
Transition = Base:new()

--Transition = {
--   _name = nil,
--   _toState = nil,
--   OnTransition = nil
--   }

-----------------------------------------------------------------------------
-- Machine Class --
-----------------------------------------------------------------------------
Machine = Base:new()

function Machine:setInitialState(initState)
    assert(initState, "can't set nil initial state")
    print (self._name .. " Set Initial State [" .. initState:getName() .. "]") 
    self._currentState = initState
end

function Machine:addState(state)
    assert(state, "can't add nil state")
    print (self._name .. " Add State [" .. state:getName() .. "]") 
    self._states = self._states or {}
    self._states[state:getName()] = state
    state._machine = self._name
end

function Machine:process(event)
    local toState = self._currentState:processEvent(event)
        if toState then
        self._previousState = self._currentState;
        self._currentState = toState
        if self._currentState.OnEnter then
            self._currentState.OnEnter(self, self._currentState, self._previousState)
        end
        print ("Transited from " .. self._previousState._name .. " -> " .. self._currentState._name)
    end
end

function Machine:clone(name)
    print ("Clone Machine [" .. self._name .. "] with Name [" .. (name or self._name) .. "]")
    local machine = Machine:new{_name = name or self._name, _currentState = self._currentState, _states = {}} 
    for stateName, state in pairs(self._states) do
        machine._states[stateName] = state 
    end
    return machine
end

-----------------------------------------------------------------------------
-- State Class --
-----------------------------------------------------------------------------
State = Base:new()

--State = {
--   _name = nil, 
--   _machine = nil,
--   _transTable = {},
--   OnEnter = nil, 
--   OnExit = nil
--   }

function State:getName()
    return self._name
end

function State:addTransition(event, toState)
    self._transTable = self._transTable or {}
    print (self._name .. " Add Transition | Event [" .. event._name .. "] | To State [" .. toState._name .. "]")
    assert(toState._machine == self._machine, "can't add transition if to state belongs to different machine")
    local transition = Transition:new{
        _name = self._name .. "_" .. event._name,
        _toState = toState,
        _isInternal = false,
        OnTransition = nil}
    self._transTable[event._name] = transition
    print("Add Transition [" .. self._transTable[event._name]._name .. "] | Transition Count: [" .. table.getn(self._transTable) .. "]")
    return transition;
end

function State:addInternalTransition(event)
    self._transTable = self._transTable or {}
    print (self._name .. " Add Internal Transition | Event [" .. event._name .. "]")
    local transition = Transition:new{
        _name = self._name .. "_" .. event._name,
        _toState = nil,
        _isInternal = true,
        OnTransition = nil}
    self._transTable[event._name] = transition   
    print("Add Transition [" .. self._transTable[event._name]._name .. "] | Transition Count: [" .. table.getn(self._transTable) .. "]")
    return transition
end

function State:getTransition(event)
    self._transTable = self._transTable or {}
    return self._transTable[event._name]
end   

function State:processEvent(event)
    self._transTable = self._transTable or {}
    local transObj = self._transTable[event._name]
    if transObj then
        if transObj._isInternal then
            print ("internal transition by transition action [" .. transObj._name .. "]")
        else
            print ("transit from " .. self._name .. " -> " .. transObj._toState._name .. " by transition action [" .. transObj._name .. "]")
            if self.OnExit then
                self.OnExit(self._machine, self)
            end
        end
        if transObj.OnTransition then
            if transObj.OnTransition(self, transObj._toState, event) then
                return transObj._toState
            end
        else
            return transObj._toState
        end
    else
        print ("no matching transition for event [" .. event._name .. "]")
    end
    return nil
end
